const Koa = require("koa");
const app = new Koa();
const Router = require("koa-router");
const router = new Router();
const mock = require("mockjs");
const BodyParser = require("koa-bodyparser");
const { list } = mock.mock({
	"list|100": [
		{
			name: "@cname",
			id: "@id",
			image: "@image(100x100)",
			"price|1-100": 1,
			"type|1": [1, 2, 3, 4, 5],
		},
	],
});
let cartList = [];
const userList = [{ username: "kkk", password: 123, role: "admin" }];
// 改完自动重启服务 nodemon
// 获取商品列表
router.get("/list", ctx => {
	const { pageIndex, pageSize, type } = ctx.query;
	let newList = [];
	if (type) {
		newList = list.filter(item => item.type == type);
	}
	newList = newList.slice((pageIndex - 1) * pageSize, pageIndex * pageSize);
	// ctx = {request,response}
	ctx.body = newList; //的 ctx.response.body 简写
});
// 获取详情
router.get("/list/:id", ctx => {
	const { id } = ctx.params;
	const detail = list.find(item => item.id == id);
	ctx.body = detail;
});
// 加入购物车
router.get("/cart/add", async ctx => {
	const { id, image, name, price, count } = ctx.query;
	const data = cartList.find(item => item.id == id);
	if (data) {
		data.count += 1;
	} else {
		cartList.push({ ...ctx.query, count: 1 });
	}
	ctx.body = {
		success: true,
		message: "添加成功",
	};
});
// 获取购物车列表
router.get("/cart/list", async ctx => {
	ctx.body = cartList;
});
// 修改购物车商品数量
router.get("/cart/setcount", async ctx => {
	const { id, count } = ctx.query;
	const ind = cartList.findIndex(item => item.id == id);
	cartList[ind].count = count;
	ctx.body = {
		success: true,
		message: "修改成功",
	};
});
// 删除购物车商品
router.post("/cart/delete", async ctx => {
	const { idList } = ctx.request.body;
	cartList = cartList.filter(item => idList.indexOf(item.id) == -1);
	ctx.body = {
		success: true,
		message: "删除成功",
	};
});
// 登录
router.get("/register", ctx => {
	const { username, password } = ctx.query;
	const isHave = userList.some(
		item => item.username == username && item.password == password
	);
	if (isHave) {
		ctx.body = {
			success: true,
			message: "登录成功",
			token: 123,
		};
	} else {
		ctx.body = {
			success: false,
			message: "登录失败",
		};
	}
});
// 注册
router.get("/register", ctx => {
	const { username, password } = ctx.query;
	userList.push({ username, password });
	ctx.body = {
		success: true,
		message: "注册成功",
	};
});

// 如果你要用post 你需要下载postman进行调试
// 下载一个koa-bodyparser的包 否则post参数无法被解析
app.use(BodyParser()); // 需要比router先注册
app.use(router.routes());

app.listen(8888, () => {
	console.log("listen to 8888");
});
// query ctx.query
// params ctx.parmas
// body ctx.request.body
